<template>
	<view class="">
		<!-- 登錄 -->
		<authorize @onLoadFun="onLoadFun" isGoIndex></authorize>
		
		<view class="content">
			<!-- 菜单 (悬浮,预先隐藏)-->
			<tabs-sticky v-if="isShowSticky" v-model="tabIndex" :fixed="true" :tabs="navList" @change="changeTab"></tabs-sticky>
			<mescroll-body ref="mescrollUni" @init="mescrollInit" class="app-mescroll" :up="upOption" :down="downOption" @down="downCallback" @up="upCallback">
				<!--轮播-->
				<swiper style="min-height: 300rpx" autoplay="true" interval="3000" duration="300" circular="true">
					<swiper-item v-for="(swiper, i) in swiperList" :key="i">
						<image :src="fileUrl + swiper.path" @tap="toSwiper(swiper)" mode="widthFix" style="width: 100%"></image>
					</swiper-item>
				</swiper>
				<!-- 菜单 (在mescroll-uni中不能使用fixed,否则iOS滚动时会抖动, 所以需在mescroll-uni之外存在一个一样的菜单) -->
				<view id="tabInList"><tabs-sticky v-model="tabIndex" :tabs="navList" @change="changeTab"></tabs-sticky></view>
				<view class="app-container">
					<view class="card no-card cu-card dynamic" v-for="(item, index) in navList[tabIndex].pdList" :key="index" :index="index" @tap.stop="toReleasedDetails(navList[tabIndex].pdList[index])">
						<view class="solid-bottom margin-bottom">
							<text class="margin-right-xs text-bold">{{ item.demand_type_describe }}</text>
							<text class="cu-tag line-default radius sm">{{ item.status | filterStatus }}</text>
							<text class="cu-tag line-red radius sm" v-if="item.print_order_status && item.print_order_status === 6">{{ item.print_order_status === 6 && navList[tabIndex].type === 3 ? '文件已打印, 如非本人打印请提交申诉' : '' }}</text>
						</view>
						<view class="gray-bg">
							<view class="text-gray margin-bottom-xs">
								<text class="margin-right-xs">所在区域: </text>
								{{ item.area_name }}
							</view>
							<view class="text-gray margin-bottom-xs">
								<text class="margin-right-xs">收货地址: </text>
								{{ item.shipping_address }}
							</view>
							<view class="text-gray margin-bottom-xs">
								<text class="margin-right-xs">创建时间: </text>
								{{ item.create_time }}
							</view>
							<view class="text-gray margin-bottom-xs">
								<text class="margin-right-xs">商品总价: </text>
								￥{{ item.price}}
							</view>
							<view class="text-gray margin-bottom-xs">
								<text class="margin-right-xs">实付款: </text>
								￥{{ item.actual_price}} {{item.tip > 0 ? '( 外加小费' + item.tip+ '元 )' : ''}}
							</view>
						</view>
						<view class="fr margin-top-sm">
							<button @tap.stop="payMethod(navList[tabIndex].pdList[index])" class="cu-btn radius sm bg-gray margin-right-xs" v-if="item.status === 0">支付</button>
							<button @tap.stop="rewardModalEvent(navList[tabIndex].pdList[index])" class="cu-btn radius sm bg-gray margin-right-xs" v-if="item.status === 1  && navList[tabIndex].type === 2 || item.status === 9  && navList[tabIndex].type === 2 || item.status === 8 && navList[tabIndex].type === 2">打赏</button>
							<button @tap.stop="cancelEvent(navList[tabIndex].pdList[index])" class="cu-btn radius sm bg-gray margin-right-xs" v-if="item.status === 1 || item.status === 0 || item.status === 9">取消</button>
							<button @tap.stop="confirmDeliveryEvent(navList[tabIndex].pdList[index])" class="cu-btn radius sm bg-gray margin-right-xs" v-if="item.status === 3 && navList[tabIndex].type === 3">确认送达</button>
							<button @tap.stop="userConfirmDeliveryEvent(navList[tabIndex].pdList[index])" class="cu-btn radius sm bg-gray margin-right-xs" v-if="item.status === 4 && navList[tabIndex].type === 2">确认收货</button>
							<button @tap.stop="feedbackEvent(navList[tabIndex].pdList[index])" class="cu-btn radius sm bg-gray margin-right-xs" v-if="item.status === 3 || item.status === 4">申请退款</button>
						</view>
					</view>
				</view>
			</mescroll-body>
		</view>
		<PaymentModal ref="PaymentModal" title="校验安全密码" v-model="payFlag" @confirm="confirmPassword"></PaymentModal>
		<view class="cu-modal bottom-modal" :class="{ show: isReward }" @tap="hideModal">
			<view class="cu-dialog" @tap.stop="">
				<view class="cu-bar bg-white">
					<view class="action text-blue" @tap="hideModal">取消</view>
					<view class="action text-green" @tap="confirmPay">支付</view>
				</view>
				<view class="padding-sm">
					<view class="card-wrap" :class="{ 'isIphoneX-class': isIphoneX }">
						<view class="item" v-for="(item, index) in prices" :key="index" :class="{ active: index === currentIndex }" @tap="selectTip(item, index)">
							<img :src="item.icon" alt="" />
							<view class="text-xl margin-top-xs">
								<text class="text-xs">￥</text>
								{{ item.price }}
							</view>
						</view>
						<view class="text">
							<text class="title">打赏骑手</text>
							<text class="dec">您的小费将直接转给骑手</text>
						</view>
						<view class="text">
							<text class="title">支付方式</text>
							<radio-group @change="radioChange" class="fr dec">
								<radio value="2" style="transform:scale(0.5)" :checked="paymentMethod === '2'" />
								微信支付
								<radio value="1" style="transform:scale(0.5)" :checked="paymentMethod === '1'" />
								余额支付
							</radio-group>
						</view>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
import TabsSticky from './components/tabs-sticky.vue';
import MescrollBody from '@/components/mescroll-uni/mescroll-body.vue';
import MescrollMixin from '@/components/mescroll-uni/mescroll-mixins.js';
import { getCommunityDemandInfoList, confirmDelivery, wechatUserConfirmDelivery, changeNoDemandOrderStatus } from '@/api/community.js';
import PaymentModal from '@/components/payment-modal/password.vue';
import { paymentInterface } from '@/api/pay';
import { mapGetters } from 'vuex';
import { getAdvertising } from '@/api/common.js';
import { VUE_APP_BASE_API } from '@/common/tools/config.js';
import authorize from '@/components/authorize/authorize.vue';

export default {
	mixins: [MescrollMixin],
	components: {
		TabsSticky,
		MescrollBody,
		PaymentModal,
		authorize
	},
	onLoad(options) {
		this.tabIndex = Number(options.index || 0);
		this.getAdvertisingEvent()
	},
	data() {
		return {
			fileUrl: VUE_APP_BASE_API,
			swiperList: [],
			upOption: {
				auto: false,
				empty: {
					icon: "/static/img/noOrder.png"
				}
				// 如果用mescroll-uni 则需要onScroll: true, 且需要 @scroll="scroll"; 而mescroll-body最简单只需在onPageScroll处理即可
				// onScroll: true // 是否监听滚动事件, 默认false (配置为true时,可@scroll="scroll"获取到滚动条位置和方向)
			},
			downOption: {
				auto: false, //是否在初始化后,自动执行下拉回调callback; 默认true
				native: true // 启用系统自带的下拉组件,默认false;仅mescroll-body生效,mescroll-uni无效
			},
			isReward: false,
			payFlag: false,
			tabIndex: 0, // 当前菜单下标
			preIndex: 0, // 前一个菜单下标
			navTop: null, // nav距离到顶部的距离 (如计算不准确,可直接写死某个值)
			isShowSticky: false, 
			navList: [
				{ name: '我提交的', type: 2, pdList: null, num: 1, y: 0, curPageLen: 0, hasNext: true },
				{ name: '我接单的', type: 3, pdList: null, num: 1, y: 0, curPageLen: 0, hasNext: true }
			],
			prices: [
				{
					icon:
						'',
					price: '0.01'
				},
				{
					icon:
						'',
					price: '2.2'
				},
				{
					icon:
						'',
					price: '3.3'
				},
				{
					icon:
						'',
					price: '6.6'
				}
			],
			list: [],
			paymentMethod: '2',
			currentIndex: 0,
			row: {},
			orderType: 2
		};
	},
	filters: {
		filterStatus(value) {
			const orderStates = {
				0: '未支付',
				1: '等待接单',
				2: '已取消',
				3: '配送中',
				4: '已送达',
				5: '申诉中',
				6: '退款中',
				7: '已退款',
				8: '已确认收货',
				9: '待审核订单',
				10: '审核不通过订单'
			};
			return orderStates[value];
		},
		filterPrice(value, tip) {
			const total = Number(value) + Number(tip)
			return total.toFixed(2)
		}
	},
	// onShow() {
	// 	this.mescroll.resetUpScroll();
	// },
	computed: {
		...mapGetters(['isIphoneX'])
	},
	// 使用mescroll-body最简单只需在onPageScroll处理即可
	onPageScroll(e){
		if (e.scrollTop >= this.navTop) {
			this.isShowSticky = true // 显示悬浮菜单
		} else {
			this.isShowSticky = false // 隐藏悬浮菜单
		}
	},
	methods: {
		onLoadFun() {
			this.mescroll.resetUpScroll();
		},
		/**
		 * 查询社区需求信息列表
		 */
		getCommunityDemandInfoListEvent({ pageSize, currentPage }) {
			return new Promise((resolve, reject) => {
				getCommunityDemandInfoList({
					status: [0,1,2,3,4,5,6,7,8,9,10],
					type: this.navList[this.tabIndex].type,
					pageSize: pageSize,
					currentPage: currentPage
				})
					.then(res => {
						resolve(res.result);
					})
					.catch(err => {
						reject(err);
					});
			});
		},
		/*下拉刷新的回调 */
		downCallback() {
			this.mescroll.resetUpScroll();
		},
		/*上拉加载的回调: mescroll携带page的参数, 其中num:当前页 从1开始, size:每页数据条数,默认10 */
		upCallback(page) {
			//联网加载数据
			if (this.isChangeTab) {
				this.mescroll.hideUpScroll(); // 切换菜单,不显示mescroll进度, 显示系统进度条
				uni.showLoading();
			}

			const { num, size } = page;
			this.getCommunityDemandInfoListEvent({
				pageSize: size,
				currentPage: num
			})
				.then(result => {
					// 当前tab数据
					let curTab = this.navList[this.tabIndex];
					const curPageData = result.showing;
					//设置列表数据
					if (num == 1) curTab.pdList = []; //如果是第一页需手动制空列表
					this.navList[this.tabIndex].pdList = curTab.pdList.concat(result.showing);
					this.mescroll.endBySize(curPageData.length, result.total);
					// 数据渲染完毕再隐藏加载状态
					this.$nextTick(() => {
						curTab.num = num; // 页码
						curTab.curPageLen = curPageData.length; // 当前页长
						curTab.hasNext = this.mescroll.optUp.hasNext; // 是否还有下一页

						// 设置nav到顶部的距离 (需根据自身的情况获取navTop的值, 这里放到列表数据渲染完毕之后)
						// 也可以放到onReady里面,或者菜单顶部的数据(轮播等)加载完毕之后..
						if (!this.navTop) this.setNavTop();
						// 保持tab悬浮,列表数据显示第一条
						if (this.isChangeTab) {
							this.isChangeTab = false;
							uni.hideLoading();
							if (this.isShowSticky) this.mescroll.scrollTo(this.navTop, 0);
						}
					});
				})
				.catch(err => {
					// 失败隐藏下拉加载状态
					this.mescroll.endErr();
				});
		},
		// 设置nav到顶部的距离 (滚动条为0, 菜单顶部的数据加载完毕获取到的navTop数值是最精确的)
		setNavTop() {
			let view = uni
				.createSelectorQuery()
				.in(this)
				.select('#tabInList');
			view.boundingClientRect(data => {
				this.navTop = data.top; // 到屏幕顶部的距离
			}).exec();
		},
		// 点击回到顶部按钮时,先隐藏悬浮菜单,避免闪动
		topClick() {
			this.isShowSticky = false;
		},
		//顶部tab点击
		tabClick(index) {
			this.tabCurrentIndex = index;
		},

		// 切换菜单
		changeTab(index) {
			// 记录前一个菜单的数据
			let preTab = this.navList[this.preIndex];
			preTab.y = this.mescroll.getScrollTop(); // 滚动条位置
			this.preIndex = index;
			// 当前菜单的数据
			let curTab = this.navList[index];
			if (!curTab.pdList) {
				// 没有初始化,则初始化
				this.isChangeTab = true;
				this.mescroll.resetUpScroll();
			} else {
				// 初始化过,则恢复之前的列表数据
				this.mescroll.setPageNum(curTab.num + 1); // 恢复当前页码
				this.mescroll.endSuccess(curTab.curPageLen, curTab.hasNext); // 恢复是否有下一页或显示空布局
				this.$nextTick(() => {
					this.mescroll.scrollTo(curTab.y, 0); // 恢复滚动条的位置
				});
			}
		},
		toReleasedDetails(item) {
			uni.navigateTo({
				url: `/user-pages/released-details?demand_order_id=${item.demand_order_id}`,
				success: res => {},
				fail: () => {},
				complete: () => {}
			});
		},
		/**
		 * 选择消费
		 * @param {Object} item
		 */
		selectTip(item, index) {
			this.currentIndex = index;
		},
		/**
		 * 打开打赏选择页面
		 */
		rewardModalEvent(row) {
			this.row = row;
			this.orderType = 3;
			this.isReward = true;
		},
		/**
		 * 确认打赏
		 */
		confirmPay() {
			this.hideModal();
			const paymentMethod = this.paymentMethod;
			paymentMethod === '2' && this.wechatPay();
			paymentMethod === '1' && this.balancePay();
		},
		/**
		 * 选择支付方式
		 */
		payMethod(row) {
			this.row = row;
			this.orderType = 2;
			uni.showActionSheet({
				itemList: ['微信支付', '余额支付'],
				success: res => {
					this.paymentMethod = res.tapIndex === 0 ? '2' : '1';
					res.tapIndex === 0 && this.wechatPay();
					res.tapIndex === 1 && this.balancePay();
				}
			});
		},
		/**
		 * 有订单号时 微信支付
		 */
		wechatPay() {
			//第一步: 获取支付参数
			this.paymentInterfaceEvent().then(result => {
				//第二步：发起微信支付
				this.payEvent(result);
			});
		},
		/**
		 * 余额支付
		 */
		balancePay() {
			//验证密码
			this.payFlag = true;
		},
		/**
		 *  获取支付流水号
		 */
		paymentInterfaceEvent(password) {
			return new Promise(resolve => {
				const row = this.row;
				paymentInterface({
					payType: Number(this.paymentMethod),
					body: row.demand_type_name,
					out_trade_no: this.orderType === 2 ? row.order_number : '',
					order_id: row.demand_order_id || '',
					payment_code: password || '',
					orderType: this.orderType,
					tip: this.orderType === 3 ? this.prices[this.currentIndex].price : ''
				}).then(res => {
					resolve(res.result);
				});
			});
		},
		/**
		 * 调起微信支付
		 * @param result
		 */
		payEvent(result) {
			const { nonceStr, paySign, signType, timeStamp } = result;
			wx.requestPayment({
				nonceStr: nonceStr,
				package: result.package,
				paySign: paySign,
				signType: signType,
				timeStamp: timeStamp.toString(),
				success: res => {
					if (res.errMsg === 'requestPayment:ok') {
						uni.showToast({
							title: '支付成功',
							icon: 'success',
							duration: 6000
						});
						this.$refs.mescrollUni.mescroll.resetUpScroll();
					}
				},
				fail: res => {
					if (res.errMsg !== 'requestPayment:fail cancel') {
						uni.showModal({
							title: '支付错误',
							content: '可能遇到网络堵塞，建议重新尝试提交预约'
						});
					}
				}
			});
		},
		/**
		 * 输入密码后确认事件
		 * @param {Object} value 密码
		 */
		confirmPassword(value) {
			//支付
			this.paymentInterfaceEvent(value).then(res => {
				uni.showToast({
					title: '支付成功',
					icon: 'success',
					duration: 6000
				});
				this.$refs.PaymentModal.hideModal();
				this.$refs.mescrollUni.mescroll.resetUpScroll();
			});
		},
		hideModal() {
			this.isReward = false;
		},
		radioChange(evt) {
			this.paymentMethod = evt.target.value;
		},
		/**
		 * 取消
		 * type 操作类型，1为取消未支付需求订单，2为自行退款未接单订单
		 */
		cancelEvent(item) {
			changeNoDemandOrderStatus({
				demand_order_id: item.demand_order_id,
				type: item.status === 0 ? 1 : 2
			}).then(res => {
				uni.showToast({
					title: '已成功撤回, 感谢您的使用',
					icon: 'success',
					duration: 6000
				});
				this.$refs.mescrollUni.mescroll.resetUpScroll();
			})
		},
		/**
		 * 反馈
		 */
		feedbackEvent(item) {
			uni.navigateTo({
				url: '/user-pages/feedbackDetail?type=3&orderId=' + item.demand_order_id
			});
		},
		/**
		 * 骑手确认送达
		 * @param {Object} item 选择的订单
		 */
		confirmDeliveryEvent(item) {
			confirmDelivery({
				demand_order_id: item.demand_order_id
			}).then(res => {
				this.$refs.mescrollUni.mescroll.resetUpScroll();
				uni.showModal({
					title: '确认已送达',
					content: '等待需求者确认收货或三天后自动确认收货，感谢您和需求者的互爱互助',
					showCancel: false
				});
			})
		},
		/**
		 * 用户确认收货
		 * @param {Object} item 选择的订单
		 */
		userConfirmDeliveryEvent(item) {
			wechatUserConfirmDelivery({
				demand_order_id: item.demand_order_id
			}).then(res => {
				this.$refs.mescrollUni.mescroll.resetUpScroll();
				uni.showModal({
					title: '确认已送达',
					content: '钱款会自动打入骑手账户，感谢您和骑手的互爱互助',
					showCancel: false
				});
			})
		},
		//查询广告栏图片数组
		getAdvertisingEvent() {
			getAdvertising({
				//1为'我的'页面广告位，2为'我发布的'页面广告位
				advertisingType: 2
			}).then(res => {
				this.swiperList = res.result.path
			})
		},
		//轮播图跳转
		toSwiper(swiper) {
			if(swiper.advertising_type === 0) {
				const src = encodeURIComponent(swiper.url);
				uni.navigateTo({
					url: `/pages/web-view?src=${src}`
				})
				
			}else if(swiper.advertising_type === 1) {
				uni.navigateTo({
					url: swiper.url
				})
			}
			
		},
	}
};
</script>

<style lang="scss">
	.app-mescroll {
		width: 100%;
	}
.content {
	width: 100%;
	.navbar {
		display: flex;
		height: 80upx;
		box-shadow: 0 1px 5px rgba(0, 0, 0, 0.06);
		position: relative;
		z-index: 10;
		.nav-item {
			flex: 1;
			display: flex;
			justify-content: center;
			align-items: center;
			height: 100%;
			font-size: 15px;
			position: relative;
			&.current {
				color: $uni-hover;
				&:after {
					content: '';
					position: absolute;
					left: 50%;
					bottom: 0;
					transform: translateX(-50%);
					width: 75px;
					height: 0;
					border-bottom: 2px solid $uni-hover;
				}
			}
		}
	}
}
.gray-bg {
	background: #a5c3f730;
	border-radius: 5px;
	padding: 10px;
}
.card-wrap {
	width: 100%;
	.item {
		height: 90px;
		width: 23%;
		padding: 10px;
		display: inline-block;
		vertical-align: top;
		background: #a5c3f730;
		margin: 1%;
		border-radius: 5px;
		color: #172575;
		image {
			width: 80rpx;
			height: 80rpx;
		}
	}
	.active {
		border: solid 1px #a5c3f7;
	}
	.text {
		display: flex;
		justify-content: space-between;
		margin: 2%;

		.title {
			font-size: 12px;
			text-align: left;
			color: #172575;
		}
		.dec {
			font-size: 12px;
			text-align: right;
			color: #c1c1c1;
		}
	}
}
</style>
